import random
from django.shortcuts import render
import logging

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from . import constants

logger = logging.getLogger('django')

# Create your views here.
class SMSCodeView(APIView):

    """
    发送短信验证码
    """

    def get(self, request, mobile):

        """
        # GET  sms_codes/(?P<mobile>1[3-9]\d{9}/
        :param request: Request类的请求对象
        :param mobile: 手机号码
        :return: Response
        """

        # 连接redis数据库
        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' %mobile)

        if send_flag:

            return Response({'message':'频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info(sms_code)


        #创建reidis管道
        pl = redis_conn.pipeline()
        # 保存短信验证码
        pl.setex('sms_%s' %mobile, constants.SMS_CODE_REDIS_EXPIRE, sms_code)
        # 保存短信发送标志
        pl.setex('send_flag_%s' %mobile, constants.SEND_FLAG_TIME_INTERVAL, 1)
        #执行管道
        pl.execute()

        return Response({'message':'ok'})
